package com.amap.map.util.locationSource;

import android.content.ContentValues;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.map.network.handler.CustomExecutorService;
import com.amap.map.network.handler.DataUploadHandler;
import com.amap.map.util.AMapUtil;
import com.amap.map.util.Configuration;
import com.amap.map.util.OffLineMapUtils;
import com.amap.map.util.ToastUtil;
import com.amap.map.util.common.StringUtils;
import com.amap.map.util.common.database.DatabaseHandler;
import com.amap.map.vo.Json;
import com.amap.map.vo.localtion.LocationInfo;

/****
 * 代理定位处理
 * @author liuxing
 *
 */
public class LocationSourceProxy implements LocationSource , AMapLocationListener {
	
	AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private LocationManagerProxy mAMapLocationManager;
    Context context;
	
	public LocationSourceProxy(AMap aMap , Context context){
        this.context = context;
        this.aMap = aMap ;
	    initAmapSeting() ;
    }

	@Override
	public void onLocationChanged(Location arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLocationChanged(AMapLocation location ) {
		if (mListener != null && location != null) {
			mListener.onLocationChanged(location);// 显示系统小蓝点
			//http://code.autonavi.com/Public/reference/LocSDK/com/amap/api/location/AMapLocation.html
			double geoLat = location.getLatitude();		//纬度
			double geoLng = location.getLongitude();	//经度
//			String cityCode = "";
//			String desc = "";
//			Bundle locBundle = location.getExtras();
//			if (locBundle != null) {
//				cityCode = locBundle.getString("citycode");
//				desc = locBundle.getString("desc");
//			}
//			StringBuffer message = new StringBuffer("定位成功:(") ;
//			message.append( geoLng ).append( "," ).append( geoLat ).append( ")" ) ;
//			message.append( "\n精    度    :" ).append( location.getAccuracy() ).append( "米" );
//			message.append( "\n定位方式:" ).append( location.getProvider()  ).append( "\n定位时间:" ) ;
//			message.append( AMapUtil.convertToTime(location.getTime())  ).append( "\n城市编码:" ) ;
//			message.append( cityCode  ).append( "\n位置描述:"  ).append( desc  ).append( "\n省:" ) ;
//			message.append( location.getProvince()  ).append( "\n市:"  ).append( location.getCity() ) ;
//			message.append( "\n区(县):"  ).append( location.getDistrict()  ).append( "\n区域编码:"  ).append( location.getAdCode() );
//			ToastUtil.show( context.getApplicationContext() , message.toString() );
			if( geoLng>0.00001 && geoLat>0.00001 ){
				ContentValues contentValues = new ContentValues();
	            contentValues.put( "localtionx" , geoLng );
	            contentValues.put( "localtiony" , geoLat );
				new DatabaseHandler(context).oneDataTable("location", contentValues);	//成功后纪录相关的数据信息
				CustomExecutorService.getInstance().execute( new DataUploadHandler( geoLng,geoLat ,this) );
			}
		}
	}

	/****
	 * localtion activity
	 * 每一次定位都会触发这里,于是要改变客户端定位的频率会变得相对简单
	 */
	@Override
	public void activate(OnLocationChangedListener onLocationChangedListener) {
		 mListener = onLocationChangedListener ;
	     if (mAMapLocationManager == null) {
	            mAMapLocationManager = LocationManagerProxy.getInstance(context);
//	            
//	            Criteria cri = new Criteria();   
//	            cri.setAccuracy(Criteria.ACCURACY_COARSE); 
//	            cri.setAltitudeRequired(false);  
//	            cri.setBearingRequired(false);  
//	            cri.setCostAllowed(false); 
//	            String bestProvider = mAMapLocationManager.getBestProvider(cri, true);  
//	            mAMapLocationManager.requestLocationUpdates(bestProvider, 10000, 10, this );
			/*
			 * mAMapLocManager.setGpsEnable(false);
			 * 1.0.2版本新增方法，设置true表示混合定位中包含gps定位，false表示纯网络定位，默认是true Location
			 * API定位采用GPS和网络混合定位方式
			 * ，第一个参数是定位provider，第二个参数时间最短是2000毫秒，第三个参数距离间隔单位是米，第四个参数是定位监听者
			 * 第二个参数指的是多久的时间间隔定位一次
			 */
			mAMapLocationManager.requestLocationData( LocationProviderProxy.AMapNetwork, 10000, 10, this );
			mAMapLocationManager.setGpsEnable(false);
		}
	}
	
	/****
	 * 网络请求后回调函数处理
	 * 可以处理服务端反馈的信息 ----- 待议
	 * @param message
	 */
	public void callBackMethod( String message ){
		Json location = JSON.parseObject( message , Json.class);
		if( location.isSuccess() && !StringUtils.isEmpty( location.getMsg() ) ){
//			deactivate() ;
//	        mAMapLocationManager = LocationManagerProxy.getInstance(context);
//			mAMapLocationManager.requestLocationData( LocationProviderProxy.AMapNetwork, 3000 , 10, this );
//			mAMapLocationManager.setGpsEnable(false);
		}
	}

	/****
	 * localtion dead
	 */
	@Override
	public void deactivate() {
		mListener = null;
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(this);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	/***
	 * 初始化部分设置的参数
	 */
	private void initAmapSeting(){
		//MapsInitializer.sdcardDir =OffLineMapUtils.getSdCacheDir(this);
		UiSettings setting = aMap.getUiSettings();
		setting.setMyLocationButtonEnabled(true);	//开启定位按钮显示
		setting.setCompassEnabled( true ) ;			//开启指南针 
		setting.setScaleControlsEnabled( true ) ;	//开启比例尺功能
		aMap.setMyLocationEnabled(true);			// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW );	//跟随定位，将定位点置为中心点
		//加载退出时的位置信息，作为启动的中心点位置
		LocationInfo info = new DatabaseHandler( context ).query() ;
		if( info != null && info.getLocaltionx() > 0.00001 && info.getLocaltiony() > 0.00001 ){	//第一次安装时将显示的是北京的地理位置
			LatLng latlng = new LatLng( info.getLocaltiony() , info.getLocaltionx() );
			aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng,12));
		}
		//aMap.addMarker(new com.amap.api.maps.model.MarkerOptions().position(latlng).draggable(true) ); 放一个标记点
	}
}
